import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Device } from 'src/entities/Device';
import { LocalCacheService } from 'src/local-cache/local-cache.service';
import { Repository } from 'typeorm';

@Injectable()
export class DeviceService {
    constructor(
        @InjectRepository(Device) protected repository:Repository<Device>,
        private localCache:LocalCacheService
    ){}

    async device(simCardNo:string) {
        let device:Device
        const key = 'dev:' + simCardNo
        const cache = await this.localCache.store.get(key)
        if(cache) {
            device = JSON.parse(cache)
        }else {
            device = await this.repository.findOne({
                where : {simCardNo}
            })

            if(device) {
                this.localCache.store.set(key, JSON.stringify(device), {EX : 30*60})
            }
        }

        return device
    }
}
